package com.ruoyi.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.admin.domain.entity.AtricleModel;
import com.ruoyi.admin.domain.entity.FlawModel;
import com.ruoyi.admin.domain.entity.InventoryModel;
import com.ruoyi.admin.domain.entity.ProfitModel;
import com.ruoyi.admin.mapper.AtricleMapper;
import com.ruoyi.admin.mapper.InventoryMapper;
import com.ruoyi.admin.mapper.ProfitMapper;
import com.ruoyi.admin.domain.vo.response.flaw.FlawPageResponse;
import com.ruoyi.admin.domain.vo.response.flaw.FlawResponse;
import com.ruoyi.admin.mapper.FlawMapper;
import com.ruoyi.admin.service.FlawService;
import com.ruoyi.common.api.Result;
import com.ruoyi.common.api.ResultCode;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 瑕疵表(Flaw)Service实现类
 *
 * @author jianhan
 * @date 2023-01-31 09:53:25
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class FlawServiceImpl extends ServiceImpl<FlawMapper, FlawModel> implements FlawService {

    private static final Logger logger = LoggerFactory.getLogger(FlawServiceImpl.class);

    @Resource
    private InventoryMapper inventoryMapper;

    @Resource
    private ProfitMapper profitMapper;

    @Resource
    private AtricleMapper atricleMapper;
    @Override
    public Result<FlawResponse> getId(Long flawId) {
        FlawModel flawModel = this.getById(flawId);
        if (flawModel != null) {
            FlawResponse flawResponse = new FlawResponse(flawModel);
            return Result.success(flawResponse);
        }
        return Result.failed(ResultCode.DATA_NOT_EXIST);
    }

    @Override
    public Result<FlawPageResponse> page(Page<FlawModel> page, FlawModel searchModel) {
        QueryWrapper<FlawModel> queryWrapper = queryWrapper(searchModel);

        Page<FlawModel> pages = this.page(page, queryWrapper);
        FlawPageResponse flawPageResponse = new FlawPageResponse(pages);
        page.getRecords().forEach((flawModel) -> flawPageResponse.getRecords().add(new FlawResponse(flawModel)));
        return Result.success(flawPageResponse);

    }

    @Override
    public Result add(FlawModel flawModel) {
        List<AtricleModel> atricleModels = atricleMapper.selectList(new QueryWrapper<AtricleModel>().eq("id", flawModel.getArticleId()));
        if (atricleModels!=null&&atricleModels.size() > 0) {
            AtricleModel atricleModel = atricleModels.get(0);
            List<AtricleModel> atricleModels1 = atricleMapper.selectList(new QueryWrapper<AtricleModel>().eq("article_number", atricleModel.getArticleNumber()).eq("size", flawModel.getSize()));
            if (atricleModels1!=null&&atricleModels1.size() > 0) {
                flawModel.setArticleId(atricleModels1.get(0).getId());
            }
        }
        flawModel.setState("10");
        List<InventoryModel> inventoryModels = inventoryMapper.selectList(new QueryWrapper<InventoryModel>().eq("atricle_id", flawModel.getArticleId()));
        if (inventoryModels!=null&&inventoryModels.size()>0){
            InventoryModel inventoryModel = inventoryModels.get(0);
            if (inventoryModel.getNumber()!=0L) {
                Boolean result = this.save(flawModel);
                if (result) {
                    return Result.success();
                }
            }else {
                return Result.failed("库存数量不够");
            }
        }else {
            return Result.failed("库存数量不够");
        }

        return Result.failed("添加失败");
    }

    @Override
    public Result update(FlawModel flawModel) {
        if (flawModel.getState().equals("20")) {
            //20已处理
            //修改库存
            List<InventoryModel> inventoryModels = inventoryMapper.selectList(new QueryWrapper<InventoryModel>().eq("atricle_id", flawModel.getArticleId()));
            if (inventoryModels != null && inventoryModels.size() > 0) {
                InventoryModel inventoryModel = inventoryModels.get(0);
                inventoryModel.setNumber(inventoryModel.getNumber() - 1);
                inventoryModel.setTotalPrice(inventoryModel.getTotalPrice().subtract(inventoryModel.getPrice()));
                inventoryMapper.updateById(inventoryModel);
            }
            //修改报表
            List<ProfitModel> profitModels = profitMapper.selectList(new QueryWrapper<ProfitModel>().eq("article_id", flawModel.getArticleId()));
            if (profitModels != null && profitModels.size() > 0) {
                ProfitModel profitModel = profitModels.get(0);
                profitModel.setOutputAmount(profitModel.getOutputAmount().add(flawModel.getPrice()));
                profitModel.setGrossMargin(profitModel.getGrossMargin().add(flawModel.getPrice()));
            } else {
                ProfitModel profitModel = new ProfitModel();
                profitModel.setOutputAmount(flawModel.getPrice());
                profitModel.setGrossMargin(flawModel.getPrice());
                profitMapper.insert(profitModel);
            }
        }
        int i = baseMapper.updateById(flawModel);
        if (i > 0) {
            return Result.success();
        }
        return Result.failed("更新失败");
    }

    @Override
    public Result delete(Long flawId) {
        Boolean result = this.removeById(flawId);
        return Result.judge(result);

    }

    @Override
    public Result dispose(FlawModel req) {
        if (req.getState().equals("20")) {
            //20已处理
            //修改库存
            List<InventoryModel> inventoryModels = inventoryMapper.selectList(new QueryWrapper<InventoryModel>().eq("atricle_id", req.getArticleId()));
            if (inventoryModels != null && inventoryModels.size() > 0) {
                InventoryModel inventoryModel = inventoryModels.get(0);
                inventoryModel.setNumber(inventoryModel.getNumber() - 1);
                inventoryModel.setTotalPrice(inventoryModel.getTotalPrice().subtract(inventoryModel.getPrice()));
                inventoryMapper.updateById(inventoryModel);
            }
            //修改报表
            List<ProfitModel> profitModels = profitMapper.selectList(new QueryWrapper<ProfitModel>().eq("atricle_id", req.getArticleId()));
            if (profitModels != null && profitModels.size() > 0) {
                ProfitModel profitModel = profitModels.get(0);
                profitModel.setOutputAmount(profitModel.getOutputAmount().add(req.getPrice()));
                profitModel.setGrossMargin(profitModel.getGrossMargin().add(req.getPrice()));
            } else {
                ProfitModel profitModel = new ProfitModel();
                profitModel.setOutputAmount(req.getPrice());
                profitModel.setGrossMargin(req.getPrice());
                profitMapper.insert(profitModel);
            }
        }
        int i = baseMapper.updateById(req);
        if (i > 0) {
            return Result.success();
        }
        return Result.failed("更新失败");
    }

    private QueryWrapper<FlawModel> queryWrapper(FlawModel flawModel) {
        QueryWrapper<FlawModel> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(flawModel.getState())) {
            queryWrapper.eq("state", flawModel.getState());
        }
        
        /*
           写搜索条件
        */
        queryWrapper.orderByDesc("id");
        return queryWrapper;
    }

}
